package com.hu.contoller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.hu.context.BaseContext;
import com.hu.entity.dto.GenerateQuestionDto;

import com.hu.entity.pojo.QuestionEntity;
import com.hu.entity.vo.Result;
import com.hu.service.QuestionService;
import com.hu.util.StringUtil;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;


import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping("question")
@Slf4j
public class QuestionController {

    @Autowired
    private ChatClient chatClient;

    @Autowired
    QuestionService questionService;

    /**
     * 同步生成题目(用户要等待)
     * @param generateQuestionDto
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("/generateQuestion")
    public String generateQuestion(@RequestBody GenerateQuestionDto generateQuestionDto) throws JsonProcessingException {
        System.out.println("接收到用户的请求：" + generateQuestionDto.toString());
        String content = chatClient.prompt()
                .system("你是一个精通各行各业的专家，擅长于针对各行各业进行出题，考试，题目解析等")
                                .user("帮我出" + generateQuestionDto.getQuestionNum() + "道" +
                                        generateQuestionDto.getQuestion() + "的题目，" +
                                        generateQuestionDto.getQuestionFormat() )
                                .call().content();
        content = content.replaceAll("```json","").replaceAll("```","");
        System.out.println("大模型返回的内容：" + content);
        ObjectMapper objectMapper = new ObjectMapper();
        // 将字符串解析成对象
        List<QuestionEntity> questionEntities = objectMapper.readValue(content,new TypeReference<List<QuestionEntity>>() {});
        questionService.saveQuestions(questionEntities);
        return content;

    }

    /**
     * 异步生成题目(用户可以在等待的时候做其他事情)
     * @param generateQuestionDto
     * @return
     * @throws JsonProcessingException
     */
    @PostMapping("asyncGenerateQuestion")
    public Result<String> asyncGenerateQuestion(@RequestBody GenerateQuestionDto generateQuestionDto) throws JsonProcessingException {
        log.info("接收用户的请求：{}", generateQuestionDto.toString());
        Long userId = generateQuestionDto.getUserId();
        log.info("当前用户的id:{}",userId);
        String uuid = StringUtil.uuid();
        Future<Boolean> booleanFuture = questionService.generateQuestion(generateQuestionDto, uuid, userId);// 异步执行的
        try {
            Boolean success = booleanFuture.get(); // 阻塞获取异步结果
            if (success == null || !success) {
                return Result.fail("生成失败,达到容量,请充值扩容后再尝试");
            }
        } catch (InterruptedException | ExecutionException e) {
            log.error("异步生成题目时发生异常", e);
            return Result.fail("生成题目时发生系统错误");
        }
        return Result.success("题目正在生成中，请稍后查看",uuid);
    }

    /**
     * 根据生成id查询题目
     * @param generateId
     * @return
     * @throws JsonProcessingException
     */
    @GetMapping("list/{generateId}")
    public Result<List<QuestionEntity>>
    listByGenerateId(@PathVariable("generateId") String generateId) throws
            JsonProcessingException {
        List<QuestionEntity> questionEntities =
                questionService.selectByGenerateId(generateId);
        return Result.success(questionEntities);
    }

    /**
     * 收藏题目或者加入错题集
     */
    @GetMapping("addCollection/{id}")
    public Result<String> addCollection(@PathVariable("id") Integer id,Integer status,Integer operation) {
        questionService.addCollection(id,status,operation);
        return Result.success("收藏成功");
    }

    /**
     * 根据不同类型查找题目
     * @param status
     * @return
     */
    @GetMapping("/getQuestions")
    public Result<List<QuestionEntity>> getQuestions(@RequestParam(required = false) Integer status,Long userId){
        log.info("根据不同类型查找题目,status:{},userId:{}",status,userId);
        List<QuestionEntity> list=questionService.getQuestions(status,userId);
        return Result.success(list);

    }

    /**
     * 删除题目
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public Result<String> deleteQuestion(@PathVariable Integer id,Long userId){
        log.info("删除题目,id:{}",id);
        questionService.deleteQuestion(id,userId);
        return Result.success("删除成功");
    }

}
